package Control;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import Entity.Shop_Customization;
import Form.Shop_Customization_Canvas;
import Form.Shop_Customization_Form;

public class Shop_Customization_Control {
	
	private Shop_Customization_Form parser;
	
	public void saveCustomization(Shop_Customization_Form parser){
		
		setParser(parser);
		
		String custId = CommonControls.generateDefaultType5DigitCode('C');
		
		String frontImageUrl = canvasToImage(parser.getFrontView(), "front_"+custId);
		String backImageUrl = canvasToImage(parser.getBackView(), "back_"+custId);
		
		Shop_Customization customization;
		
		if(parser.getParser() != null){
			customization = new Shop_Customization(frontImageUrl, backImageUrl, parser.getProduct(), custId, parser.getParser().getControl().getOrder().getOrderId(), (Integer)parser.getQuantity().getValue());
			parser.getParser().getControl().getOrder().getCustomizations().add(customization);
		}
		else{
			customization = new Shop_Customization(frontImageUrl, backImageUrl, parser.getProduct(), custId, parser.getSecondaryParser().getControl().getOrder().getOrderId(), (Integer)parser.getQuantity().getValue());
			parser.getSecondaryParser().getControl().getOrder().getCustomizations().add(customization);
		}
	}
	
	/*
	 * Convert canvas to image
	 * @return url of saved image
	 */
	public static String canvasToImage(Shop_Customization_Canvas toConvert, String filename){
		
		BufferedImage image = new BufferedImage(toConvert.getWidth(), toConvert.getHeight(), BufferedImage.TYPE_INT_ARGB);
		
		Graphics2D graphics = image.createGraphics();
		
		toConvert.print(graphics);
		
		graphics.dispose();
		
		try {
			ImageIO.write(image, "png", new File("Resources/Images/Custom/"+filename+".png"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return "Resources/Images/Custom/"+filename+".png";
		
	}

	public Shop_Customization_Form getParser() {
		return parser;
	}

	public void setParser(Shop_Customization_Form parser) {
		this.parser = parser;
	}

}
